package com.wus.gateway.config.filter;

import cn.hutool.json.JSONUtil;
import com.wus.common.core.account.AccountThreadLocal;
import com.wus.common.core.constant.AccountConstants;
import com.wus.common.core.domain.user.AccountInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description: 添加请求头过滤器
 * @Author: wus
 * @Date: 2024/12/18 11:13
 */
@Component
public class AddHeaderFilter implements GlobalFilter, Ordered {

    private final Logger logger = LoggerFactory.getLogger(AddHeaderFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        logger.info("---------- AddHeaderFilter");
        // 非feign下的网关路由，FeignHeaderInterceptor不适用；需要过滤器添加请求头参数ACCOUNT_INFO_CONTEXT_HEADER
        AccountInfo accountInfo = AccountThreadLocal.get();
        ServerHttpRequest request = exchange.getRequest().mutate().header(AccountConstants.ACCOUNT_INFO_CONTEXT_HEADER, JSONUtil.toJsonStr(accountInfo)).build();
        // 把新的exchange放回到过滤链
        return chain.filter(exchange.mutate().request(request).build());
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
